<template>
  <section>
    <div class="select-popup">
      <template v-if="inputPopup">
        <el-row>
          <el-col :span="20"
            ><el-input
              v-model="copyInputStyle.inputValue"
              :disabled="outInputStyle.disabled"
              :placeholder="outInputStyle.placeholder"
            ></el-input
          ></el-col>
          <el-col :span="4"
            ><el-button type="primary" @click="openPopup">{{
              outCommonSetting.btnText
            }}</el-button></el-col
          >
        </el-row>
        <el-dialog
          :title="outPopupStyle.title"
          :width="outPopupStyle.width"
          :modal-append-to-body="outPopupStyle['modal-append-to-body']"
          :append-to-body="outPopupStyle['append-to-body']"
          :default-expand-all="outTreeQuery['default-expand-all']"
          :visible.sync="showPopup"
        >
          <el-tabs
            v-if="tabList.length > 1"
            v-model="activeName"
            @tab-click="handleClick"
          >
            <el-tab-pane
              :label="item.label"
              :name="item.name"
              v-for="(item, index) in tabList"
              :key="index"
            ></el-tab-pane>
          </el-tabs>
          <el-row>
            <el-col :span="10">
              <el-input
                v-model="searchValueLeft"
                placeholder="请输入关键字搜索"
                @change="searchNode({ type: 'left' })"
                v-if="!(outTreeStyle.height && !outCommonSetting.onlineSearch)"
              ></el-input>
              <div
                class="border-box height480 margin-top10"
                :style="{
                  height: outTreeStyle.height
                    ? outTreeStyle.height + 'px'
                    : '480px'
                }"
              >
                <femessage-tree
                  ref="tree"
                  :data="outTreeStyle.data"
                  :height="outTreeStyle.height"
                  :lazy="outTreeStyle.lazy"
                  :load="outTreeStyle.load"
                  :node-key="outTreeStyle['node-key']"
                  :props="outTreeStyle.props"
                  :render-after-expand="outTreeStyle['render-after-expand']"
                  :highlight-current="outTreeStyle['highlight-current']"
                  :default-expand-all="outTreeStyle['default-expand-all']"
                  :expand-on-click-node="outTreeStyle['expand-on-click-node']"
                  :check-on-click-node="outTreeStyle['check-on-click-node']"
                  :auto-expand-parent="outTreeStyle['auto-expand-parent']"
                  :default-expanded-keys="outTreeStyle['default-expanded-keys']"
                  :show-checkbox="outTreeStyle['show-checkbox']"
                  :check-strictly="outTreeStyle['check-strictly']"
                  :default-checked-keys="outTreeStyle['default-checked-keys']"
                  :current-node-key="outTreeStyle['current-node-key']"
                  :filter-node-method="outTreeStyle['filter-node-method']"
                  :accordion="outTreeStyle.accordion"
                  :indent="outTreeStyle.indent"
                  :icon-class="outTreeStyle['icon-class']"
                  :draggable="outTreeStyle.draggable"
                  @node-expand="nodeExpand"
                  @node-collapse="nodeCollapse"
                  @check-change="checkChange"
                  @check="check"
                  @node-click="nodeClick(arguments, 'left')"
                >
                  <template slot-scope="{ node, data }">
                    <div
                      class="tree-content"
                      v-if="!$scopedSlots.treecontent && !$slots.treecontent"
                    >
                      <div class="icon-box">
                        <i
                          :class="{
                            'el-icon-folder':
                              data.type == 'org' && !node.expanded,
                            'el-icon-folder-opened':
                              data.type == 'org' && node.expanded,
                            'el-icon-user': data.type == 'user'
                          }"
                        ></i>
                      </div>
                      <div class="text">
                        {{ data.name
                        }}<span v-if="data.type == 'org'"
                          >（{{ data.userCount }}人）</span
                        >
                      </div>
                    </div>
                    <slot
                      v-else
                      name="treecontent"
                      v-bind:treeData="data"
                      v-bind:treeNode="node"
                    ></slot>
                  </template>
                </femessage-tree>
              </div>
            </el-col>
            <el-col :span="4">
              <div
                class="flex center height480"
                :style="{
                  height: outTreeStyle.height
                    ? outTreeStyle.height + 'px'
                    : '480px'
                }"
              >
                <el-button
                  icon="el-icon-arrow-right"
                  :type="leftCurrentData.length ? 'primary' : 'info'"
                  @click="borderChange({ type: 'left' })"
                >
                </el-button>
                <el-button
                  icon="el-icon-arrow-left"
                  :type="rightCurrentData.length ? 'primary' : 'info'"
                  @click="borderChange({ type: 'right' })"
                >
                </el-button>
                <el-button
                  icon="el-icon-caret-right"
                  @click="borderChange({ type: 'leftAll' })"
                >
                </el-button>
                <el-button
                  icon="el-icon-caret-left"
                  :type="rightData.length ? 'primary' : 'info'"
                  @click="borderChange({ type: 'rightAll' })"
                >
                </el-button>
              </div>
            </el-col>
            <el-col :span="10"
              ><el-input
                v-model="searchValueRight"
                placeholder="请输入关键字搜索"
                @change="searchNode({ type: 'right' })"
                v-if="!(outTreeStyle.height && !outCommonSetting.onlineSearch)"
              ></el-input>
              <div
                class="border-box height480 margin-top10"
                :style="{
                  height: outTreeStyle.height
                    ? outTreeStyle.height + 'px'
                    : '480px'
                }"
              >
                <femessage-tree
                  ref="rightTree"
                  :data="outRightData"
                  :height="outTreeStyle.height"
                  :expand-on-click-node="outTreeStyle['expand-on-click-node']"
                  :node-key="outTreeStyle['node-key']"
                  :highlight-current="outTreeStyle['highlight-current']"
                  :filter-node-method="outTreeStyle['filter-node-method']"
                  @node-click="nodeClick(arguments, 'right')"
                >
                  <template slot-scope="{ node, data }">
                    <div
                      class="tree-content"
                      v-if="
                        !$scopedSlots.righttreecontent && !$slots.treecontent
                      "
                    >
                      <div class="icon-box">
                        <i
                          :class="{
                            'el-icon-folder':
                              data.type == 'org' && !node.expanded,
                            'el-icon-folder-opened':
                              data.type == 'org' && node.expanded,
                            'el-icon-user': data.type == 'user'
                          }"
                        ></i>
                      </div>
                      <div class="text">
                        {{ data.name
                        }}<span v-if="data.type == 'org'"
                          >（{{ data.userCount }}人）</span
                        ><span v-else>（{{ data.deptName }}）</span>
                      </div>
                    </div>
                    <slot
                      v-else
                      name="righttreecontent"
                      v-bind:treeData="data"
                      v-bind:treeNode="node"
                    ></slot>
                  </template>
                </femessage-tree>
              </div>
            </el-col>
          </el-row>
          <div class="footer-btn">
            <el-row type="flex" class="row-bg" justify="end">
              <el-col :span="4"
                ><el-button type="primary" @click="confirmPopup"
                  >确认</el-button
                ></el-col
              >
              <el-col :span="4"
                ><el-button type="info" @click="canclePopup"
                  >取消</el-button
                ></el-col
              >
            </el-row>
          </div>
        </el-dialog>
      </template>
      <template v-else>
        <el-tabs
          v-if="tabList.length > 1"
          v-model="activeName"
          @tab-click="handleClick"
        >
          <el-tab-pane
            :label="item.label"
            :name="item.name"
            v-for="(item, index) in tabList"
            :key="index"
          ></el-tab-pane>
        </el-tabs>
        <el-row>
          <el-col :span="10">
            <el-input
              v-model="searchValueLeft"
              placeholder="请输入关键字搜索"
              @change="searchNode({ type: 'left' })"
              v-if="!(outTreeStyle.height && !outCommonSetting.onlineSearch)"
            ></el-input>
            <div
              class="border-box height480 margin-top10"
              :style="{
                height: outTreeStyle.height
                  ? outTreeStyle.height + 'px'
                  : '480px'
              }"
            >
              <femessage-tree
                ref="tree"
                :key="treeKey"
                :data="outTreeStyle.data"
                :lazy="outTreeStyle.lazy"
                :load="outTreeStyle.load"
                :height="outTreeStyle.height"
                :node-key="outTreeStyle['node-key']"
                :props="outTreeStyle.props"
                :render-after-expand="outTreeStyle['render-after-expand']"
                :highlight-current="outTreeStyle['highlight-current']"
                :default-expand-all="outTreeStyle['default-expand-all']"
                :expand-on-click-node="outTreeStyle['expand-on-click-node']"
                :check-on-click-node="outTreeStyle['check-on-click-node']"
                :auto-expand-parent="outTreeStyle['auto-expand-parent']"
                :default-expanded-keys="outTreeStyle['default-expanded-keys']"
                :show-checkbox="outTreeStyle['show-checkbox']"
                :check-strictly="outTreeStyle['check-strictly']"
                :default-checked-keys="outTreeStyle['default-checked-keys']"
                :current-node-key="outTreeStyle['current-node-key']"
                :filter-node-method="outTreeStyle['filter-node-method']"
                :accordion="outTreeStyle.accordion"
                :indent="outTreeStyle.indent"
                :icon-class="outTreeStyle['icon-class']"
                :draggable="outTreeStyle.draggable"
                @node-expand="nodeExpand"
                @node-collapse="nodeCollapse"
                @check-change="checkChange"
                @check="check"
                @node-click="nodeClick(arguments, 'left')"
              >
                <template slot-scope="{ node, data }">
                  <div
                    class="tree-content"
                    v-if="!$scopedSlots.treecontent && !$slots.treecontent"
                  >
                    <div class="icon-box">
                      <i
                        :class="{
                          'el-icon-folder':
                            data.type == 'org' && !node.expanded,
                          'el-icon-folder-opened':
                            data.type == 'org' && node.expanded,
                          'el-icon-user': data.type == 'user'
                        }"
                      ></i>
                    </div>
                    <div class="text">
                      {{ data.name
                      }}<span v-if="data.type == 'org'"
                        >（{{ data.userCount }}人）</span
                      >
                    </div>
                  </div>
                  <slot
                    v-else
                    name="treecontent"
                    v-bind:treeData="data"
                    v-bind:treeNode="node"
                  ></slot>
                </template>
              </femessage-tree>
            </div>
          </el-col>
          <el-col :span="4">
            <div
              class="flex center height480"
              :style="{
                height: outTreeStyle.height
                  ? outTreeStyle.height + 'px'
                  : '480px'
              }"
            >
              <el-button
                icon="el-icon-arrow-right"
                :type="leftCurrentData.length ? 'primary' : 'info'"
                @click="borderChange({ type: 'left' })"
              >
              </el-button>
              <el-button
                icon="el-icon-arrow-left"
                :type="rightCurrentData.length ? 'primary' : 'info'"
                @click="borderChange({ type: 'right' })"
              >
              </el-button>
              <el-button
                icon="el-icon-caret-right"
                @click="borderChange({ type: 'leftAll' })"
              >
              </el-button>
              <el-button
                icon="el-icon-caret-left"
                :type="rightData.length ? 'primary' : 'info'"
                @click="borderChange({ type: 'rightAll' })"
              >
              </el-button>
            </div>
          </el-col>
          <el-col :span="10"
            ><el-input
              v-model="searchValueRight"
              placeholder="请输入关键字搜索"
              @change="searchNode({ type: 'right' })"
              v-if="!(outTreeStyle.height && !outCommonSetting.onlineSearch)"
            ></el-input>
            <div
              class="border-box height480 margin-top10"
              :style="{
                height: outTreeStyle.height
                  ? outTreeStyle.height + 'px'
                  : '480px'
              }"
            >
              <femessage-tree
                ref="rightTree"
                :data="outRightData"
                :height="outTreeStyle.height"
                :node-key="outTreeStyle['node-key']"
                :highlight-current="outTreeStyle['highlight-current']"
                :filter-node-method="outTreeStyle['filter-node-method']"
                @node-click="nodeClick(arguments, 'right')"
              >
                <template slot-scope="{ node, data }">
                  <div
                    class="tree-content"
                    v-if="!$scopedSlots.righttreecontent && !$slots.treecontent"
                  >
                    <div class="icon-box">
                      <i
                        :class="{
                          'el-icon-folder':
                            data.type == 'org' && !node.expanded,
                          'el-icon-folder-opened':
                            data.type == 'org' && node.expanded,
                          'el-icon-user': data.type == 'user'
                        }"
                      ></i>
                    </div>
                    <div class="text">
                      {{ data.name
                      }}<span v-if="data.type == 'org'"
                        >（{{ data.userCount }}人）</span
                      ><span v-else>（{{ data.deptName }}）</span>
                    </div>
                  </div>
                  <slot
                    v-else
                    name="righttreecontent"
                    v-bind:treeData="data"
                    v-bind:treeNode="node"
                  ></slot>
                </template>
              </femessage-tree>
            </div>
          </el-col>
        </el-row>
      </template>
    </div>
  </section>
</template>

<script>
import _ from "lodash";
export default {
  name: "userSelectIndex",

  directives: {},
  props: {
    value: {
      type: [Array, String],
      default: []
    },
    // 是否展示输入框来选择
    inputPopup: {
      type: [Boolean],
      default: true
    },
    // 输入框配置
    inputStyle: {
      type: [Object],
      default: function() {
        return {};
      }
    },
    // 弹框配置
    popupStyle: {
      type: [Object],
      default: function() {
        return {};
      }
    },
    // 树状图配置
    treeStyle: {
      type: [Object],
      default: function() {
        return {};
      }
    },
    // 通用配置
    commonSetting: {
      type: [Object],
      default: function() {
        return {};
      }
    },
    // tab切换设置不同的api
    tabList: {
      type: [Array],
      default: function() {
        return [
          {
            label: "全部",
            name: "0"
          }
        ];
      }
    },
    // api
    loadApi: {
      type: [String, Boolean],
      default: "getOrganizeLazy"
    },
    // 懒加载
    treeLoad: {
      type: [Function],
      default: function(obj = {}) {
        let { node, resolve, _this } = obj;
        let { data } = node;
        let params = this.outTreeQuery;
        if (data) {
          let { origId, type, pid } = data;
          params.parentId = origId || 0;
        }
        this.API[this.loadApi](params).then(res => {
          resolve(res.data);
          this.$nextTick(() => {
            _this.getRightNode();
            // _this.getValueNode();
          });
        });
      }
    },
    // 搜索树状数据
    onlineSearch: {
      type: [Function],
      default: function(obj = {}) {
        let { keywords, _this } = obj;
        let params = _.cloneDeep(this.outTreeQuery);
        params.parentId = 0;
        params.keywords = keywords;
        this.API[this.loadApi](params).then(res => {
          this.outTreeStyle.data = res.data;
          this.$nextTick(() => {
            _this.getRightNode();
            // _this.getValueNode();
          });
        });
      }
    },
    treeQuery: {
      type: [Object],
      default: function() {
        return {
          parentId: 0,
          type: 1,
          module: "",
          keywords: "",
          queryType: "ALL",
          flag: ""
        };
      }
    }
  },
  data() {
    return {
      showPopup: false,
      activeName: "0",
      searchValueLeft: "",
      // 搜索后选中的数据,需要在懒加载的时候使用
      searchCheckData: {},
      searchCheckArr: [],
      searchValueRight: "",
      leftData: [],
      rightData: [],
      leftCurrentData: [],
      rightCurrentData: [],
      // 树组件key值
      treeKey: 0,
      // 记录搜索状态
      searchStatus: 0,
      // 弹框默认配置
      copyPopupStyle: {
        title: "选择组织机构和人员",
        width: "800px",
        "modal-append-to-body": false,
        "append-to-body": true,
        modal: true,
        fullscreen: false,
        top: "15vh",
        "lock-scroll": true,
        "close-on-click-modal": true,
        "close-on-press-escape": true,
        "show-close": true,
        "before-close": function(done) {
          done();
        },
        center: false,
        "destroy-on-close": false
      },
      // 输入框默认配置
      copyInputStyle: {
        inputValue: "",
        type: "text",
        maxlength: -1,
        minlength: -1,
        "show-word-limit": false,
        placeholder: "请输入内容",
        clearable: false,
        "show-password": false,
        disabled: true,
        size: "medium",
        "prefix-icon": "",
        "suffix-icon": "",
        rows: 2,
        autosize: false,
        autocomplete: false,
        name: "",
        readonly: false,
        max: -1,
        min: -1,
        step: ""
      },
      // 树状图默认配置
      copyTreeStyle: {
        data: [],
        "empty-text": "暂无数据",
        "node-key": "origId",
        props: {
          label: "name",
          isLeaf: function(data, node) {
            if (data.type == "user") {
              return true;
            }
            return false;
          }
        },
        "render-after-expand": true,
        load: function(node, resolve) {
          resolve([]);
        },
        "highlight-current": true,
        "default-expand-all": false,
        "expand-on-click-node": false,
        "check-on-click-node": false,
        "auto-expand-parent": true,
        "default-expanded-keys": [],
        "show-checkbox": true,
        "check-strictly": false,
        "default-checked-keys": [],
        "current-node-key": "",
        "filter-node-method": function(value, data) {
          if (!value) {
            return true;
          }
          return data.name.indexOf(value) !== -1;
        },
        accordion: false,
        indent: 16,
        "icon-class": "",
        lazy: true,
        draggable: false,
        "allow-drag": function(node) {
          return false;
        }
      },
      copyCommonSetting: {
        onlineSearch: true,
        btnText: "选择"
      },
      // 最终配置
      outTreeQuery: {},
      outInputStyle: {},
      outPopupStyle: {},
      outTreeStyle: {},
      outCommonSetting: {}
    };
  },
  computed: {
    outRightData() {
      let _this = this;
      let allArr = [...this.rightData, ...this.searchCheckArr];
      let outArr = _.unionBy(allArr, function(o) {
        return o[_this.outTreeStyle["node-key"]];
      });
      // console.log(outArr)
      if (!outArr[0]) {
        outArr = [];
      }
      // console.log('bbb',new Date().getTime());
      return this.handleTreeData({ checkedNodes: outArr, justReturn: true });
    }
  },
  watch: {
    loadApi(n, o) {
      this.init();
    },
    inputStyle: {
      // 监听设置组件属性
      handler: function(n, o) {
        this.setInputStyle();
      },
      deep: true
    },
    popupStyle: {
      // 监听设置组件属性
      handler: function(n, o) {
        this.setPopupStyle();
      },
      deep: true
    },
    treeStyle: {
      // 监听设置组件属性
      handler: function(n, o) {
        this.setTreeStyle();
      },
      deep: true
    },
    commonSetting: {
      // 监听设置通用属性
      handler: function(n, o) {
        this.setCommonSetting();
        if (n.searchLoading) {
          this.$nextTick(() => {
            this.getRightNode();
          });
        }
      },
      deep: true
    },
    onlineSearchData: {
      // 监听搜索数据
      handler: function(n, o) {
        // console.log(n)
        this.$nextTick(() => {
          this.getRightNode();
        });
      },
      deep: true
    },
    showPopup(n, o) {
      if (n) {
        this.$nextTick(() => {
          if (!this.outTreeStyle.data.length) {
            this.getTreeData();
          }
          this.getValueNode();
          this.defaultOpen();
        });
      }
    },
    outRightData: {
      handler: function(n, o) {
        if (!this.inputPopup) {
          this.confirmPopup();
        }
      },
      deep: true
    }
  },

  mounted() {
    this.init();
  },

  methods: {
    init() {
      // 初始化
      this.setInputStyle();
      this.setPopupStyle();
      this.setTreeStyle();
      this.setCommonSetting();
      this.setTreeQuery();
      this.setTreeLoad();
      this.treeKey++;
    },
    // 设置懒加载参数
    setTreeQuery() {
      this.$set(this.$data, "outTreeQuery", this.treeQuery);
    },
    // 设置懒加载函数
    setTreeLoad() {
      let _this = this;
      if (this.loadApi) {
        this.$set(this.outTreeStyle, "load", function(node, resolve) {
          _this.treeLoad({ node, resolve, _this });
        });
      }
    },
    setInputStyle() {
      // 设置输入框属性
      this.$set(
        this.$data,
        "outInputStyle",
        Object.assign(this.copyInputStyle, this.inputStyle)
      );
    },

    setPopupStyle() {
      // 设置弹框属性
      this.$set(
        this.$data,
        "outPopupStyle",
        Object.assign(this.copyPopupStyle, this.popupStyle)
      );
    },
    setTreeStyle() {
      // 设置树组件属性
      this.$set(
        this.$data,
        "outTreeStyle",
        Object.assign(this.copyTreeStyle, this.treeStyle)
      );
    },
    setCommonSetting() {
      // 设置组件通用属性
      this.$set(
        this.$data,
        "outCommonSetting",
        Object.assign(this.copyCommonSetting, this.commonSetting)
      );
    },
    // 如果非懒加载就直接设置data
    getTreeData() {
      if (!this.outTreeStyle.lazy && this.loadApi) {
        let params = this.outTreeQuery;
        this.API[this.loadApi](params).then(res => {
          this.outTreeStyle.data = res.data;
          this.$nextTick(() => {
            this.getRightNode();
          });
        });
      }
    },
    // 如果只有一个顶级节点，自动展开一级
    defaultOpen() {
      let nodes = this.$refs.tree._data.root.childNodes;
      if (!nodes.length) {
        setTimeout(() => {
          this.defaultOpen();
        }, 500);
        return;
      }
      if (nodes.length > 1) {
        return;
      }
      let arr = [];
      for (let i = 0; i < nodes.length; i++) {
        arr.push(nodes[i].data[this.outTreeStyle["node-key"]]);
      }
      this.$set(this.outTreeStyle, "default-expanded-keys", arr);
    },
    // 根据右侧数据来回显
    getRightNode() {
      this.$refs.tree.setCheckedNodes(this.outRightData);
    },
    // 根据value值来回显（重新打开弹框）
    getValueNode() {
      if (!this.value) {
        return;
      }
      if (!this.value.length) {
        return;
      }
      let nodes = this.$refs.tree._data.root.childNodes;
      if (!nodes.length) {
        setTimeout(() => {
          this.getValueNode();
        }, 500);
        return;
      }
      if (typeof this.value == "string") {
        let arr = this.value.split(",");
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(arr);
          let nodes = this.$refs.tree.getCheckedNodes();
          this.handleTreeData({ checkedNodes: nodes });
          this.copyInputStyle.inputValue = this.getRightText();
        });
        return;
      }
      this.handleTreeData({ checkedNodes: this.value });
      this.$nextTick(() => {
        this.getRightNode();
        this.copyInputStyle.inputValue = this.getRightText();
      });
    },
    // 确认操作
    confirmPopup() {
      this.$emit("input", this.outRightData);
      this.$emit("confirm", this.outRightData);
      this.copyInputStyle.inputValue = this.getRightText();
      this.showPopup = false;
    },
    // 获取要展示的字符串
    getRightText() {
      let arr = [];
      for (let i = 0; i < this.outRightData.length; i++) {
        arr.push(this.outRightData[i][this.outTreeStyle.props.label]);
      }
      return arr.join(",");
    },
    // 取消操作
    canclePopup() {
      this.showPopup = false;
    },
    // 搜索节点
    searchNode(obj = {}) {
      let { type } = obj;
      if (type == "left") {
        this.$refs.tree.setCurrentKey(null);
        this.leftCurrentData = [];
        if (this.outCommonSetting.onlineSearch) {
          if (this.loadApi) {
            this.onlineSearch({ keywords: this.searchValueLeft, _this: this });
            this.searchCheckData.copy_right_data = this.rightData;
          }
          // 后台接口搜索
          this.$emit("onlineSearch", { keywords: this.searchValueLeft });
        } else {
          this.$refs.tree.filter(this.searchValueLeft);
        }
      }
      if (type == "right") {
        this.$refs.rightTree.filter(this.searchValueRight);
      }
    },
    // 节点展开
    nodeExpand(data, node, ele) {},
    // 节点关闭
    nodeCollapse(data, node, ele) {},
    // 节点选框被点击
    check(data, nodeStatus) {
      // console.log(data, nodeStatus)
      let node = this.$refs.tree.getNode(data[this.outTreeStyle["node-key"]]);
      if (node) {
        let { check } = node;
        if (!check) {
          this.removeRightData({ nodeArr: [node] });
        }
      }
      let { checkedNodes } = nodeStatus;
      this.handleTreeData({ data, checkedNodes });
    },
    // 节点选中状态变化时
    checkChange(data, selfCheck, childCheck) {},
    // 节点被点击
    nodeClick(event, type) {
      let data = event[0];
      let node = event[1];
      if (type == "left") {
        this.leftCurrentData = [{ data, node }];
      }
      if (type == "right") {
        this.rightCurrentData = [{ data, node }];
      }
    },
    // 处理选中的数据做分级处理(需使用和父级对应的唯一标识)
    handleTreeData(obj = {}) {
      let { checkedNodes, justReturn } = obj;
      let arr = [];
      checkedNodes.forEach(item => {
        for (let index in checkedNodes) {
          if (item.pid === checkedNodes[index][this.outTreeStyle["node-key"]]) {
            return false;
          }
        }
        arr.push(item);
      });
      if (justReturn) {
        return arr;
      }
      if (this.searchValueLeft) {
        this.searchCheckData[this.searchValueLeft] = arr;
      } else {
        this.rightData = arr;
      }
      this.saveSearchData();
      this.$nextTick(() => {
        if (this.rightCurrentData.length) {
          for (let i = 0; i < this.rightCurrentData.length; i++) {
            this.$refs.rightTree.setCurrentKey(
              this.rightCurrentData[i].data[this.outTreeStyle["node-key"]]
            );
          }
        }
      });
    },
    // 如果为懒加载搜索，需要保存各种状态下的选中数据同时处理数据
    saveSearchData() {
      let arr = [];
      let keyArr = [];
      let outArr = [];
      for (let item in this.searchCheckData) {
        arr.push(...this.searchCheckData[item]);
      }
      // arr.push(...this.rightData);
      for (let i = 0; i < arr.length; i++) {
        if (!keyArr.includes(arr[i][this.outTreeStyle["node-key"]])) {
          keyArr.push(arr[i][this.outTreeStyle["node-key"]]);
          outArr.push(arr[i]);
        }
      }
      this.searchCheckArr = this.handleTreeData({
        checkedNodes: outArr,
        justReturn: true
      });
    },
    // 左右穿梭
    borderChange(obj = {}) {
      let { type } = obj;
      if (type == "left") {
        for (let i = 0; i < this.leftCurrentData.length; i++) {
          if (this.leftCurrentData[i].node.checked) {
            this.$message(
              `${
                this.leftCurrentData[i].data[this.outTreeStyle.props.label]
              }已选中`
            );
            this.$refs.tree.setCurrentKey(null);
            continue;
          }
          this.$refs.tree.setChecked(
            this.leftCurrentData[i].data[this.outTreeStyle["node-key"]],
            true,
            true
          );
        }
        this.$refs.tree.setCurrentKey(null);
        this.leftCurrentData = [];
      }
      if (type == "right") {
        for (let i = 0; i < this.rightCurrentData.length; i++) {
          this.$refs.tree.setChecked(
            this.rightCurrentData[i].data[this.outTreeStyle["node-key"]],
            false,
            true
          );
        }
        this.removeRightData({ nodeArr: this.rightCurrentData });
        this.rightCurrentData = [];
      }
      if (type == "leftAll") {
        // console.log('aaa',new Date().getTime());
        let nodes = this.$refs.tree._data.root.childNodes;
        let arr = [];
        for (let i = 0; i < nodes.length; i++) {
          arr.push(nodes[i].data[this.outTreeStyle["node-key"]]);
        }
        this.$refs.tree.setCheckedKeys(arr);
      }
      if (type == "rightAll") {
        for (let i = 0; i < this.rightData.length; i++) {
          this.$refs.tree.setChecked(
            this.rightData[i][this.outTreeStyle["node-key"]],
            false,
            true
          );
        }
        this.rightData = [];
        this.searchCheckData = {};
      }
      let nodes = this.$refs.tree.getCheckedNodes();
      this.handleTreeData({ checkedNodes: nodes });
    },
    // 根据[node]取消掉右侧数据
    removeRightData(obj = {}) {
      let { nodeArr } = obj;
      for (let i = 0; i < nodeArr.length; i++) {
        for (let n = 0; n < this.rightData.length; n++) {
          if (
            this.rightData[n][this.outTreeStyle["node-key"]] ==
            nodeArr[i].data[this.outTreeStyle["node-key"]]
          ) {
            this.rightData.splice(n, 1);
            n--;
          }
        }
        for (let item in this.searchCheckData) {
          for (let n = 0; n < this.searchCheckData[item].length; n++) {
            if (
              this.searchCheckData[item][n][this.outTreeStyle["node-key"]] ==
              nodeArr[i].data[this.outTreeStyle["node-key"]]
            ) {
              this.searchCheckData[item].splice(n, 1);
              n--;
            }
          }
        }
      }
    },
    openPopup() {
      // 弹框显隐
      this.showPopup = true;
    },
    handleClick(e) {
      // 点击tab抛出需要的数据
      this.$emit("tabClick", { ele: e });
    }
  }
};
</script>

<style lang="scss" scoped>
.footer-btn {
  margin-top: 20px;
}
.tree-content {
  display: flex;
  align-items: center;
  .text {
    margin-left: 5px;
  }
}
.border-box {
  border: 1px solid #dcdfe6;
  border-radius: 3px;
  overflow-y: auto;
  /deep/ .el-tree-node__content {
    span:first-child {
      flex-shrink: 0;
    }
  }
  /deep/ .el-tree__empty-block {
    position: absolute;
    top: 0;
  }
}
.height480 {
  height: 480px;
}
.flex {
  display: flex;
}
.flex.center {
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  flex-direction: column;
}
.flex .el-button {
  margin: 10px;
}
.margin-top10 {
  margin-top: 10px;
}
</style>
